import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserInfo, login, register } from '../api'
import router from '../router'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)

  // 初始化用户信息
  const initUserInfo = async () => {
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      token.value = storedToken
      try {
        await fetchUserInfo()
      } catch (error) {
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        logout()
        router.push('/login')
      }
    }
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await getUserInfo()
      userInfo.value = response.data
      // 可以选择是否要把用户信息也存储到localStorage
      localStorage.setItem('userInfo', JSON.stringify(response.data))
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 登录
  const handleLogin = async (credentials) => {
    const response = await login(credentials)
    setToken(response.data.token)
    await fetchUserInfo()
    return response
  }

  // 注册
  const handleRegister = async (userData) => {
    const response = await register(userData)
    // 注册成功后自动登录
    await handleLogin({
      username: userData.username,
      password: userData.password
    })
    return response
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!token.value && !!userInfo.value
  }

  return {
    token,
    userInfo,
    setToken,
    fetchUserInfo,
    handleLogin,
    handleRegister,
    logout,
    isLoggedIn,
    initUserInfo
  }
}) 